package guyubao.com.service.impl;


import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import guyubao.com.entity.dto.MessageChannelDto;
import guyubao.com.entity.vo.request.MessageChannelVoRequest;
import guyubao.com.entity.vo.response.MessageChannelVo;
import guyubao.com.mapper.MessageChannelMapper;
import guyubao.com.service.MessageChannelService;

import javax.annotation.Resource;

import guyubao.com.utils.SendPushPlusMessageUtils;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;

/**
 * @author wxa
 */
@Service
public class MessageChannelServiceImpl extends ServiceImpl<MessageChannelMapper,MessageChannelDto> implements MessageChannelService  {

    /***
     * 得到数据
     */
    @Override
    public MessageChannelVo getMessageChannel(String uId) {
        MessageChannelDto messageChannelDto = this.query().eq("uId", uId).one();
        return new MessageChannelVo(messageChannelDto.getName(),messageChannelDto.getJson());
    }

    /***
     * 修改数据
     */
    @Override
    public String updateMessageChannel(MessageChannelVoRequest vo) {
        return this.update().set("name", vo.getName())
                .set("json", vo.getJson())
                .eq("uId", vo.getUid())
                .update() ? null : "修改消息渠道出现问题,请联系管理人员！";
    }
    @Resource
    SendPushPlusMessageUtils sendPushPlusMessageUtils;
    @Override
    public String sendMessages(String txt) {
        List<MessageChannelDto> list = this.query().list();
        HashSet<String> hashSet = new HashSet<>();
        for (MessageChannelDto messageChannelDto : list) {
            String json = messageChannelDto.getJson();
            if (json == null) {
                continue;
            }
            Object token = JSONObject.parseObject(json).get("token");
            if (token != null && !token.toString().isEmpty()) {
                hashSet.add(token.toString());
            }
        }
        hashSet.forEach(token->{
            sendPushPlusMessageUtils.send(token,"群体通知",txt);
        });
        return null;
    }
}
